package com.licq.ldoc.writer.visitor.example.exampler;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.dom4j.Element;

import com.licq.ldoc.domain.AttributeType;
import com.licq.ldoc.domain.AttributeType.MapAttributeType;
import com.licq.ldoc.writer.visitor.example.Exampler;
import com.lowagie.text.BadElementException;

/**
 * 
 * @author liujian
 *
 */
public class MapperAttributeExampler extends Exampler {
	
	private org.dom4j.Element element;
	
	private Object object;
	
	private String property;
	
	private AttributeType type;
	
	private boolean required;

	public MapperAttributeExampler(Element element, Object object,
			String name, AttributeType type, boolean required) {
		this.element = element;
		this.object = object;
		this.property = name;
		this.type = type;
		this.required = required;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void create() throws BadElementException {
		Map propertyValue = (Map) super.getPropertyValue(object, property);
		if (propertyValue != null || required) {
			Element ele = this.element.addElement(property);
			Map valueMap = null;
			if (propertyValue == null) {
				valueMap = mockPropertyValue();
			} else {
				valueMap = propertyValue;
			}
			for (Object entryObj : valueMap.entrySet()) {
				Entry entry = (Entry) entryObj;
				Element entryEle = ele.addElement("entry");
				Element keyEle = entryEle.addElement("key");
				AttributeType kType = propertyValue != null ? getKeyType()
						: AttributeType.STRING;
				Exampler exampler = new BasicAttributeExampler(
					keyEle, null, "value", entry.getKey(), kType, true
				);
				exampler.create();
				Element valueEle = entryEle.addElement("value");
				AttributeType vType = propertyValue != null ? getValueType()
						: AttributeType.STRING;
				exampler = new BasicAttributeExampler(
					valueEle, null, "value", entry.getValue(), vType, true
				);
				exampler.create();
			}
		}
	}
	
	public Map<?, ?> getPropertyValue() {
		Map<?, ?> propertyValue = (Map<?, ?>) super.getPropertyValue(object, property);
		if (propertyValue == null && required) {
			propertyValue = mockPropertyValue();
		}
		return propertyValue;
	}
	
	@SuppressWarnings("unchecked")
	private Map<?, ?> mockPropertyValue() {
		Map map = new HashMap<String, String>();
		AttributeType keyType = getKeyType();
		AttributeType valueType = getValueType();
		//暂不考虑枚举类型作为Map的内嵌类型
		map.put(getDefaultPropertyValue(keyType), getDefaultPropertyValue(valueType));
		return map;
	}
	
	private AttributeType getKeyType() {
		return ((MapAttributeType) type).getKeyAttributeType();
	}

	private AttributeType getValueType() {
		return ((MapAttributeType) type).getValueAttributeType();
	}
	
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", "liuj");
		Map<?, ?> jj = (Map<?, ?>) map;
		System.out.println(jj);
	}

}








